package com.ibix.util;

import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 项目名称：CaoHai
 * <br>类描述：
 * <br>创建人：htliu
 * <br>创建时间：2017/11/16 11:47
 * <br>修改人:
 * <br>修改时间：2017/11/16 11:47
 * <br>修改备注：
 *
 * @author htliu
 * @date 2017/11/16 11:47
 */
@Component
public class Util {
    /**
     * 检查参数,未通过直接抛出异常
     *
     * @param result
     * @throws IllegalArgumentException
     */
    public void checkResult(BindingResult result) throws IllegalArgumentException {
        if (result.hasErrors()) {
            String resultStr = result.getFieldErrors().stream()
                    .map(v -> v.getField() + " " + v.getDefaultMessage())
                    .reduce((a, b) -> a + "  " + b).orElse("");
            throw new IllegalArgumentException(resultStr);
        }
    }


    /**
     * 当前时间戳，精确到秒,10位，后面补齐指定长度的编号
     *
     * @param num
     * @param minLength 最小长度
     * @return
     */
    public String generateSerialNum(long num, int minLength) {
        String date = String.valueOf(System.currentTimeMillis() / 1000);
        String postFix = String.format("%0" + minLength + "d", num);
        return date + postFix;
    }

    /**
     * 获取客户端IP地址
     *
     * @param request
     * @return
     */
    public String getIpAddress(HttpServletRequest request) {
        if (request == null) {
            return "169.254.29.25";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (ip.equals("127.0.0.1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                    ip = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }
}
